'use strict';
module.exports = {
	/**
	 * 该函数的功能是执行用户付费数据回传。
	 * 当用户支付完成后，微信支付会发送支付回调给vk-pay云函数，vk-pay处理完充值金豆或充值会员的逻辑后，调用本函数进行数据回传
	 * 
	 * client/user/pub/callback 前端调用的url参数地址
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			total_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		//把requestId和订单号存到-vktest表，出问题时方便追踪
		let requestid_log = await db.collection('vk-test').add({
			tips: "callback.js文件日志追踪",
			request_id: event.originalParam.context.requestId,
			out_trade_no: out_trade_no
		})

		//声明各广告平台的参数并给予默认值
		let douyin_percent = 100; //抖音回传比例，默认全部回传
		let url = ""; //巨量资产化小程序回传url
		let token = ""; //巨量资产化小程序回传token
		let kuaishou_percent = 100; //快手回传比例，默认全部回传
		let baidu_percent = 100; //百度回传比例，默认全部回传
		let tengxun_percent = 100; //腾讯回传比例，默认全部回传
		let uc_percent = 100; //UC回传比例，默认全部回传
		let oppo_percent = 100; //OPPO回传比例，默认全部回传
		let owner_id = "1000218511";
		let api_id = "api";
		let api_key = "api";
		let douyinMinPrice = 0; //最低回传金额
		let douyinMaxPrice = 99999; //最高回传金额
		let kuaishouMinPrice = 0;
		let kuaishouMaxPrice = 99999;
		let baiduMinPrice = 0;
		let baiduMaxPrice = 99999;
		let ucMinPrice = 0;
		let tengxunMinPrice = 0;
		let tengxunMaxPrice = 99999;
		let oppoMinPrice = 0;

		let newuser = true; //是否仅回传当日新用户的订单,默认开启
		let firstorder = true; //是否仅回传用户的第一笔订单,默认开启
		let baidu_token = "";
		let hour_backhaul = 24;

		//使用vk公共函数需现在页面顶部引入VK框架，获取今日0点时间戳
		let {
			todayStart
		} = vk.pubfn.getCommonTime(new Date());

		//======获取充值订单信息开始======
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		var orderinfo = temp_info.data[0];
		let clickid = temp_info.data[0].clickid || "";

		if (!clickid || clickid == "NoClickid" || clickid.length < 17) {
			res.tips = "不存在clickid";
			addvktest(`${res.tips}`);
			return res;
		}
		//======获取充值订单信息结束======

		//======获取回传比例开始======
		// let percent = await db.collection('a_config').where({
		// 	name: "RebackPercent",
		// 	user_id: orderinfo.invite_code || 0 //添加这条数据的代理商ID
		// }).get()

		let percent = null
		let tfurlpercent = await db.collection('a_config').where({
			name: "RebackPercent",
			tfid: orderinfo.tfid //添加这条数据的代理商ID
		}).get()

		if (tfurlpercent.data.length != 0) {
			percent = tfurlpercent
		} else {
			percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: orderinfo.invite_code || 0 //添加这条数据的代理商ID
			}).get()
		}

		if (percent.data[0]) {
			console.log("存在代理商比例数据", percent);
			url = percent.data[0].douyin_url; //抖音广告资产化回传URL
			token = percent.data[0].douyin_token; //抖音广告资产化回传token
			douyin_percent = percent.data[0].douyin || 100; //抖音回传比例
			kuaishou_percent = percent.data[0].kuaishou || 100; //快手回传比例
			baidu_percent = percent.data[0].baidu || 100; //百度回传比例
			tengxun_percent = percent.data[0].tengxun || 100; //腾讯回传比例
			uc_percent = percent.data[0].uc || 100; //UC回传比例
			oppo_percent = percent.data[0].oppo || 100; //oppo回传比例
			owner_id = percent.data[0].oppo_owner_id;
			api_id = percent.data[0].oppo_api_id;
			api_key = percent.data[0].oppo_api_key;
			newuser = percent.data[0].newuser; //是否仅回传当日新用户的订单
			firstorder = percent.data[0].firstorder; //是否仅回传用户的第一笔订单
			baidu_token = percent.data[0].baidu_token; //百度回传token
			douyinMinPrice = percent.data[0].douyinMinPrice || 0; //最低回传金额
			douyinMaxPrice = percent.data[0].douyinMaxPrice || 99999; //最高回传金额
			kuaishouMinPrice = percent.data[0].kuaishouMinPrice || 0;
			kuaishouMaxPrice = percent.data[0].kuaishouMaxPrice || 99999;
			baiduMinPrice = percent.data[0].baiduMinPrice || 0;
			baiduMaxPrice = percent.data[0].baiduMaxPrice || 99999;
			ucMinPrice = percent.data[0].ucMinPrice || 0;
			tengxunMinPrice = percent.data[0].tengxunMinPrice || 0;
			tengxunMaxPrice = percent.data[0].tengxunMaxPrice || 99999;
			oppoMinPrice = percent.data[0].oppoMinPrice || 0;
			hour_backhaul = percent.data[0].hour_backhaul || 24;
		} else {
			console.log("不存在代理商比例数据");
		}

		let randomnum = Math.floor(Math.random() * (99 - 0)) + 0; //生成一个0到99的随机数
		//======获取回传比例结束======


		//查询已支付订单数量，如已有一条以上的支付订单，则不回传数据给巨量
		let user_recharge_num = await db.collection('a_recharge').where({
			tfid: orderinfo.tfid,
			pay_status: 1,
			user_id: orderinfo.user_id
		}).count()

		//如果未开启【仅回传当日新用户的订单】，就把todayStart置为0，这样user_register_date>todayStart永远成立
		if (newuser) {
			console.log("仅回传今日新用户的充值订单,此处不return,继续执行下面逻辑");
		} else {
			todayStart = 0
			console.log("已把todayStart改为0");
		}

		//多少小时内的用户回传
		if (!newuser) {
			console.log(`仅回传新用户注册x小时订单`);
			let newsday = new Date().getTime();
			if (newsday > (orderinfo.user_register_date * 1 + 3600000 * hour_backhaul)) {
				addvktest(`用户注册大于设置时间${hour_backhaul}`);
				return res;
			}
		}

		//如果开启了仅回传用户首笔订单，当查出的已支付订单大于1时，就可以直接return。
		if (firstorder) {
			console.log("仅回传用户首笔订单");
			if (user_recharge_num.total > 1) {
				addvktest("已付费订单数量大于1，直接结束");
				return res;
			}
		}

		if (orderinfo.user_register_date < todayStart) {
			addvktest("用户注册时间早于今日0点，不执行回传");
			return res;
		}

		//========抖音回传开始========
		if (orderinfo.tg_pt == "douyin" && randomnum < douyin_percent * 1) {
			if (total_fee < douyinMinPrice * 100) {
				addvktest("低价格订单不回传抖音");
				return res;
			}
			if (total_fee > douyinMaxPrice * 100) {
				addvktest("高价格订单不回传抖音");
				return res;
			}
			//调用自定义函数进行抖音回传
			await douyin()
		}
		//========抖音回传结束========

		//========快手回传开始========
		if (orderinfo.tg_pt == "kuaishou" && randomnum < kuaishou_percent * 1) {
			if (total_fee < kuaishouMinPrice * 100) {
				addvktest("低价格订单不回传快手");
				return res;
			}
			if (total_fee > kuaishouMaxPrice * 100) {
				addvktest("高价格订单不回传快手");
				return res;
			}
			//调用自定义函数进行快手回传
			await kuaishou()
		}
		//========快手回传结束========



		//========腾讯回传开始========
		if (orderinfo.tg_pt == "tengxun" && randomnum < tengxun_percent * 1) {
			if (total_fee < tengxunMinPrice * 100) {
				addvktest("低价格订单不回传腾讯");
				return res;
			}
			if (total_fee > tengxunMaxPrice * 100) {
				addvktest("高价格订单不回传腾讯");
				return res;
			}
			//调用自定义函数进行腾讯回传
			await tengxun()
		}
		//========腾讯回传结束========

		//========百度回传开始========
		if (orderinfo.tg_pt == "baidu" && randomnum < baidu_percent * 1) {
			console.log("执行百度回传");
			if (total_fee < baiduMinPrice * 100) {
				addvktest("低价格订单不回传百度");
				return res;
			}
			if (total_fee > baiduMaxPrice * 100) {
				addvktest("高价格订单不回传百度");
				return res;
			}
			//调用自定义函数进行百度回传
			await baidu()
		}
		//========百度回传结束========



		// 业务逻辑结束-----------------------------------------------------------
		return res;

		//数据库添加回传记录
		async function addlog(platform, result) {

			let add_log = await db.collection('jl_huichuanjilu').add({
				type: "active_pay",
				platform: platform,
				user_id: orderinfo.user_id,
				tfid: orderinfo.tfid || "",
				agent_id: orderinfo.invite_code || 0,
				middleman_id: orderinfo.middleman_id || 0,
				adid: orderinfo.ad_id,
				clickid: clickid,
				money: total_fee,
				result: result,
				out_trade_no: out_trade_no,
				time: data._add_time,
				time_str: data._add_time_str
			})
		}

		//数据库添加回传中断日志
		async function addvktest(tips) {
			let addvktest = await db.collection('callback_log').add({
				tips: tips,
				out_trade_no: out_trade_no,
				total_fee: total_fee,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
		}

		async function douyin() {
			//先获取用户表信息，如果用户信息里存在clud_token,则执行2.0回传接口
			let orderUser = await db.collection('uni-id-users').where({
				_id: orderinfo.user_id
			}).get();

			if (orderUser.data[0].clue_token) {
				let nonce = 8889;
				let times = vk.pubfn.toDecimal(new Date() / 1000, 0);

				const crypto = require('crypto');
				const sha1 = crypto.createHash('sha1');

				let strList = [token, times, nonce];
				strList.sort();
				let buffer = "";
				strList.forEach(str => {
					buffer += str;
				})
				let sign = sha1.update(buffer).digest('hex');
				console.log("sign=", sign);

				let reback_url = url + "?timestamp=" + times + "&nonce=" + nonce + "&signature=" + sign;

				res.jlresult = await uniCloud.httpclient.request(reback_url, {
					method: 'POST',
					data: {
						"clue_token": orderUser.data[0].clue_token,
						"open_id": orderUser.data[0].wx_openid['mp-weixin'],
						"event_type": "2", //参考：https://bytedance.feishu.cn/docx/doxcnmjDmhXc1Vial05xpvdu9ed
						"props": {
							"pay_amount": total_fee || 1 //单位：分
						}
					},
					contentType: 'json',
					dataType: 'json'
				})
				console.log("res.jlresult=", res.jlresult);
			} else {
				// 回传支付事件给巨量
				res.jlurl = "https://analytics.oceanengine.com/api/v2/conversion"
				res.jlresult = await uniCloud.httpclient.request(res.jlurl, {
					method: 'POST',
					data: {
						"event_type": "active_pay",
						"context": {
							"ad": {
								"callback": clickid, //callback 这里需要填写的就是从启动参数里获取的 clickid
							}
						},
						"properties": {
							"pay_amount": total_fee, //回传付费金额
						},
						//附加属性回传http://event-manager.oceanengine.com/docs/8650/all_properties/
						"timestamp": _add_time
					},
					contentType: 'json',
					dataType: 'json'
				})
			}
			if (res.jlresult.data.code == 0 || res.jlresult.data.status == 200) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}
			// 回传记录入库
			addlog("douyin", res.jlresult.data)
		}

		async function kuaishou() {
			// 回传支付事件给快手广告平台
			let nows = new Date().getTime()
			let purchase_amount = orderinfo.shifu_amount / 100;
			purchase_amount = purchase_amount.toFixed(2)
			let ksurl =
				"http://ad.partner.gifshow.com/track/activate?event_type=3&purchase_amount=" +
				purchase_amount + "&event_time=" + nows + "&callback=" + clickid
			let kshuichuan_result = await uniCloud.httpclient.request(ksurl, {
				method: 'GET',
				data: {},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
			//回传返回结果为什么要加一个code？因为巨量广告的回传返回值有code,为方便后续通过code来统计回传成功次数，故在快手处也加一个code参数
			//快手返回成功形式为"result":1,"host-name":"ad-rs-bjmt-ad467.idcyz.hb1.kwaidc.com"
			if (kshuichuan_result.data.result == 1) {
				kshuichuan_result.data.code = 0
			}
			if (kshuichuan_result.data.result == 1) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}
			// 回传记录入库
			addlog("kuaishou", kshuichuan_result.data)
		}

		async function tengxun() {
			let request_id = vk.pubfn.getUniCloudRequestId();
			let look_log = await db.collection('vk-test').add({
				tips: "查看腾讯回传",
				request_id: request_id,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
			console.log("执行腾讯广告回传");
			//获取用户的callback 
			let chudian = await vk.baseDao.findByWhereJson({
				dbName: "jl_chudian",
				whereJson: {
					callback: clickid,
				}
			});
			console.log("351行=》", chudian);
			let callback_url = chudian.callback_url
			//获取用户的openid 
			let wechat_openid = chudian.wechat_openid
			//获取短剧名称
			let product_name = orderinfo.tv_name || ''
			//获取短剧的id 
			let tv = await vk.baseDao.findByWhereJson({
				dbName: "a_tv",
				whereJson: {
					tv_name: product_name,
				}
			});
			console.log("364行=》", tv);
			let product_id = tv._id
			// 回传支付事件给腾讯广告平台
			let nows = new Date().getTime()
			let ts_10 = Math.round(new Date().getTime() / 1000).toString();
			// 回传支付事件给腾讯https://docs.qq.com/pdf/DQm1PUWRHZVdudkRG?
			//回传事件类型：https://developers.e.qq.com/docs/guide/conversion/new_version/Web_api
			// let tengxunurl =
			// 	"http://tracking.e.qq.com/conv/web?clickid=" + clickid + "&action_time=" + ts_10 +
			// 	"&action_type=PURCHASE&value=" + total_fee + "&link=tracking.e.qq.com";
			let tengxunurl = callback_url
			let tengxunhuichuan_result = await uniCloud.httpclient.request(tengxunurl, {
				"headers": {
					"Content-Type": 'application/json',
					"cache-control": 'no-cache'
				},
				method: 'POST',
				data: {
					"actions": [{
						"outer_action_id": "", // （选填）客户唯一行为id
						"action_time": ts_10,
						"user_id": { // user_id， 对应小程序的openid
							"wechat_openid": wechat_openid, // 必填
							"wechat_app_id": "wxdad3b6f00b92a6c2", // 微信类上报必填，且必须通过授权。授权请参考微信数据接入
						},
						"trace": {
							"click_id": clickid // 必填 click_id
						},
						"action_type": "PURCHASE", // 必填 行为类型，下单为COMPLETE_ORDER、付费为PURCHASE
						"action_param": {
							"product_id ": product_id, //必填，书籍D， 
							"value": total_fee, //必填，付费金额（分）
							"product_name": product_name, //小说（或短剧剧名）书名，格式小说名-书城名称或者剧名-剧城名称
							"Object": "1" // 回传类型
						}
					}]
				},
				// contentType: 'json',
				// dataType: 'json'
			})

			if (tengxunhuichuan_result.status == 200) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}
			// 回传记录入库
			addlog("tengxun", tengxunhuichuan_result.data)
		}

		async function baidu() {
			let nows = new Date().getTime()
			console.log("baidu_token=", baidu_token);
			console.log("clickid=", clickid);
			// 回传支付事件给百度
			let baiduurl = "https://ocpc.baidu.com/ocpcapi/api/uploadConvertData"
			let baiduhuichuan_result = await uniCloud.httpclient.request(baiduurl, {
				method: 'POST',
				data: {
					"token": baidu_token, //无忧短剧token
					"conversionTypes": [{
						"logidUrl": "bd_vid=" + clickid,
						"newType": 118, //118=付费观剧，参考：https://dev2.baidu.com/content?sceneType=0&pageId=101207&nodeId=655
						"convertValue": total_fee, //转化金额，单位分，https://dev2.baidu.com/content?sceneType=0&pageId=101211&nodeId=658&subhead=
						"attributeSource": 0, //（转化来源：百度（0），自然流量（1），竞媒（2））
						"interactionsType": 1 //（归因请求方式，点击(1), 播放(2), 关注(3), 分享(4), 点赞(5), 曝光（6）不传使用1，默认为点击归因
					}]
				},
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})

			if (baiduhuichuan_result.data.result == 1) {
				baiduhuichuan_result.data.code = 0
			}
			if (baiduhuichuan_result.status == 200) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}
			// 回传记录入库
			addlog("baidu", baiduhuichuan_result.data)
		}





	}
}